<?php
namespace app\game\controller;
use cmf\controller\OpenApiBaseController;
use think\Db;
use yxixia\NetUtil;
/**
 * 系统的配置
 *
 * @author Administrator
 */
class SyscfgController extends OpenApiBaseController{
    private function getId(){
        $serverid = $this->serverid;
        $fieldId = $this->request->param('type');
        if(empty($fieldId)){
            $this->ajaxError(510, '缺失参数:type');
        }
        $data = Db::name('server_config_edit')->field('config_name,default_value')->where(['config_key'=>$fieldId])->find();
        if(empty($data)){
            $this->ajaxError(511, '不存在的配置类型');
        }
        $fields = ['serverid'=>$serverid,'config_key'=>$fieldId];
        $cfg = Db::name('server_config')->where($fields)->find();
        if(empty($cfg)){
            $fields['config_value']=$data['default_value'];
            $fields['config_name']=$data['config_name'];
            $fid = Db::name('server_config')->insert($fields,false,true);
        }else{
            $fid = $cfg['id'];
        }
        return $fid;
    }
    
    protected function update($field,$opt,$params){
        //set,del,add
        $data = Db::name('server_config')->find($field);
        $insert = false == $data;
        if($insert){
            $data=['config_value'=>'[]','version_local'=>0];
        }
        $opArr = explode('-', $opt,2);
        if(count($opArr)!=2){
            return ['msg'=>'op not key-value'];
        }
        $opk = $opArr[0];
        $opv = explode('.',$opArr[1]);
        $cfgv = json_decode($data['config_value'], true);
        $tmp = &$cfgv;
        $i=0;
        for(;$i<count($opv)-1;$i++){
            $val = $opv[$i];
            if(isset($tmp[$val])){
                $tmp = &$tmp[$val];
            }
        }
        $key = isset($opv[$i])?$opv[$i]:'';
        if($opk == 'add'){
            if($key){
                if(empty($tmp[$key])){
                    $tmp[$key] = [];
                }
                $tmp[$key][] = $params;
            }else{
                $tmp[] = $params;
            }
        }elseif($opk =='set'){
            if(empty($key)){
               $tmp = $params; 
            }else{
               $tmp[$key] = $params; 
            }
        }elseif($opk == 'del'){
            if(isset($tmp[$key])){
                $size = count($tmp);
                $isArr = true;
                for($i=0;$i<$size;$i++){
                    $isArr = $isArr && isset($tmp[$i]);
                    if(!$isArr){
                        break;
                    }
                }
                if($isArr){
                    array_splice($tmp, $key, 1);
                }else{
                    unset($tmp[$key]);
                }
            }
        }
        $data['config_value']=json_encode($cfgv);
        $data['version_local'] = $data['version_local']+1;
        if($insert){
            Db::name('server_config')->insert($data);
        }else{
            Db::name('server_config')->update($data);
        }
        return true;
    }
    
    public function itemIdList(){
        $items = [];
        $items[] = ['id'=>1,'name'=>'金币'];
        $items[] = ['id'=>2,'name'=>'元宝'];
        $items[] = ['id'=>3,'name'=>'奖券'];
        $items[] = ['id'=>4,'name'=>'房卡'];
        $items[] = ['id'=>5,'name'=>'现金'];
        return $items;
    }
    
    public function editPage(){
        $type = $this->request->param('type');
        if(empty($type)){
            return $this->ajaxError(510,'缺少参数，type');
        }
        $data = Db::name('server_config_edit')->where(['config_key'=>$type])->find();
        if($data){
            $gameId = $data['id'];
            $edit = Db::name('server_config_valide')->alias('v')->join('serverid_config b','v.id=b.configid')->where('b.gameid',$gameId)->select();
            $data['edit'] = $edit;
        }
        $idx = $this->request->param('idx');
        if($idx!=-1){
            $serverid = $this->serverid;
            $fields = ['serverid'=>$serverid,'config_key'=>$type];
            $cfg = Db::name('server_config')->where($fields)->find();
            if($cfg){
                $cfgv = json_decode($cfg['config_value'], true);
                if(isset($cfgv[$idx])){
                    $data['data'] = $cfgv[$idx];
                }else{
                    $data['data'] = $cfgv;
                }
            }
        }
        $this->ajaxSuccess($data);
    }
    
    public function getConfig(){
        $type = $this->request->param('type');
        if(empty($type)){
            return $this->error('缺少参数，type');
        }
        $fid = $this->getId();
        $data = Db::name('server_config')->find($fid);
        $cols = Db::name('server_config_edit')->field('show_cols')->where(['config_key'=>$type])->find();
        $title = json_decode($cols['show_cols'],true);
        $data['title'] = $title;
        $this->ajaxSuccess($data);
    }
    
    public function addCfg(){
        $fid = $this->getId();
        $str = $this->request->param('data','',null);
        $data = json_decode($str,true);
        if($data){
            //有ID的.都变成key->value
            if(isset($data['id'])){
                $idx = $data['id'];
                $this->update($fid, 'set-'.$idx, $data);
            }else{
                $this->update($fid, 'add-', $data);
            }
        }
        $this->ajaxSuccess($data);
    }
    
    public function delCfg(){
        $fid = $this->getId();
        $idx = $this->request->param('idx');
        $rs = $this->update($fid, 'del-'.$idx, null);
        $this->result($rs,0,'','json');
    }
    
    public function setCfg(){
        $fid = $this->getId();
        $idx = $this->request->param('idx','');
        $str = $this->request->param('data','',null);
        $data = json_decode($str,true);
        $rs =  $this->update($fid, 'set-'.$idx, $data);
        $this->ajaxSuccess($rs);
    }
    
    public function menu(){
        $data = Db::name('server_config_edit')->field(['config_name'=>'name','config_key'=>'type','template'=>'template','help_url'=>'help'])->where('enable_i',1)->select();
//        foreach ($data as $key=>$val){
//            if(empty($val['help'])){
//                unset($val['help']);
//                $data[$key] = $val;
//            }
//        }
        $this->ajaxSuccess($data);
    }
    
    /**
     * 服务器自动登陆
     **/
    public function login(){
        $token = $this->server['optoken'];
        $this->result($token,0,'','json');
    }
    
    /**
     * 同步云端配置到客户自己的服务器上.配置生效
     */
    public function syncServer(){
        $type = $this->request->param('type');
        if(empty($type)){
            return $this->error('缺少参数，type');
        }
        $data = Db::name('server_config')->where(['serverid'=>$this->serverid,'config_key'=>$type])->find();
        $server = $this->server;
        if($data['version_local']!=$data['version_remote']){
            $post = ['key_m'=>$data['config_key'],'name_m'=>$data['config_name'],'value_m'=>$data['config_value']];
            $rs = NetUtil::serverSettingRequest('saveConfig',$server,$post);
            Db::name('server_config')->where(['id'=>$data['id']])->update(['version_remote'=>$data['version_local']]); 
            $this->ajaxSuccess($rs);
        }
        $this->ajaxSuccess(true);        
    }
}
